package com.simplehire.service;

import com.simplehire.entity.ResumeMatchResult;
import com.simplehire.model.InterviewResult;
import com.simplehire.repository.InterviewResultRepository;
import com.simplehire.repository.ResumeMatchResultRepository;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 报告服务类 - MVP V4
 * 核心功能：生成和导出各种格式的报告
 */
@Service
public class ReportService {
    
    @Autowired
    private InterviewResultRepository interviewResultRepository;
    
    @Autowired
    private ResumeMatchResultRepository resumeMatchResultRepository;
    
    /**
     * 获取用户的面试结果
     */
    public List<InterviewResult> getUserInterviewResults(Long userId) {
        return interviewResultRepository.findByUserIdOrderByCreatedAtDesc(userId);
    }
    
    /**
     * 获取用户的匹配结果
     */
    public List<ResumeMatchResult> getUserMatchResults(Long userId) {
        return resumeMatchResultRepository.findByUserIdOrderByCreatedAtDesc(userId);
    }
    
    /**
     * 生成面试报告PDF（简化版本，返回HTML内容的字节数组）
     */
    public byte[] generateInterviewReportPdf(Long interviewId, Long userId) {
        InterviewResult interview = interviewResultRepository.findByIdAndUserId(interviewId, userId)
                .orElseThrow(() -> new RuntimeException("面试结果不存在"));
        
        // 简化版本：生成HTML报告内容
        StringBuilder htmlContent = new StringBuilder();
        htmlContent.append("<html><head><meta charset='UTF-8'><title>面试报告</title></head><body>");
        htmlContent.append("<h1>面试报告</h1>");
        htmlContent.append("<h2>基本信息</h2>");
        htmlContent.append("<p><strong>面试时间：</strong>").append(interview.getCreatedAt().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))).append("</p>");
        htmlContent.append("<p><strong>简历文件：</strong>").append(interview.getResumeFilename()).append("</p>");
        htmlContent.append("<p><strong>评分：</strong>").append(interview.getScore()).append("分</p>");
        
        htmlContent.append("<h2>AI问题</h2>");
        htmlContent.append("<div>").append(interview.getAiQuestions() != null ? interview.getAiQuestions().replace("\n", "<br>") : "无").append("</div>");
        
        htmlContent.append("<h2>用户回答</h2>");
        htmlContent.append("<div>").append(interview.getUserAnswers() != null ? interview.getUserAnswers().replace("\n", "<br>") : "无").append("</div>");
        
        htmlContent.append("<h2>AI反馈</h2>");
        htmlContent.append("<div>").append(interview.getAiFeedback() != null ? interview.getAiFeedback().replace("\n", "<br>") : "无").append("</div>");
        
        htmlContent.append("<h2>改进建议</h2>");
        htmlContent.append("<div>").append(interview.getSuggestions() != null ? interview.getSuggestions().replace("\n", "<br>") : "无").append("</div>");
        
        htmlContent.append("</body></html>");
        
        return htmlContent.toString().getBytes();
    }
    
    /**
     * 生成匹配报告PDF（简化版本，返回HTML内容的字节数组）
     */
    public byte[] generateMatchReportPdf(Long matchId, Long userId) {
        ResumeMatchResult match = resumeMatchResultRepository.findByIdAndUserId(matchId, userId)
                .orElseThrow(() -> new RuntimeException("匹配结果不存在"));
        
        // 简化版本：生成HTML报告内容
        StringBuilder htmlContent = new StringBuilder();
        htmlContent.append("<html><head><meta charset='UTF-8'><title>岗位匹配报告</title></head><body>");
        htmlContent.append("<h1>岗位匹配报告</h1>");
        htmlContent.append("<h2>基本信息</h2>");
        htmlContent.append("<p><strong>匹配时间：</strong>").append(match.getCreatedAt().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))).append("</p>");
        htmlContent.append("<p><strong>岗位：</strong>").append(match.getJobDescription().getTitle()).append("</p>");
        htmlContent.append("<p><strong>公司：</strong>").append(match.getJobDescription().getCompanyName()).append("</p>");
        
        htmlContent.append("<h2>匹配分数</h2>");
        htmlContent.append("<p><strong>总体匹配度：</strong>").append(match.getOverallScore()).append("%</p>");
        htmlContent.append("<p><strong>技能匹配度：</strong>").append(match.getSkillsScore()).append("%</p>");
        htmlContent.append("<p><strong>经验匹配度：</strong>").append(match.getExperienceScore()).append("%</p>");
        htmlContent.append("<p><strong>学历匹配度：</strong>").append(match.getEducationScore()).append("%</p>");
        
        htmlContent.append("<h2>匹配分析</h2>");
        htmlContent.append("<div>").append(match.getDetailedAnalysis() != null ? match.getDetailedAnalysis().replace("\n", "<br>") : "无").append("</div>");
        
        htmlContent.append("<h2>改进建议</h2>");
        htmlContent.append("<div>").append(match.getRecommendations() != null ? match.getRecommendations().replace("\n", "<br>") : "无").append("</div>");
        
        htmlContent.append("</body></html>");
        
        return htmlContent.toString().getBytes();
    }
    
    /**
     * 生成综合报告Excel
     */
    public byte[] generateComprehensiveReportExcel(Long userId) {
        try (Workbook workbook = new XSSFWorkbook()) {
            // 创建面试结果工作表
            Sheet interviewSheet = workbook.createSheet("面试结果");
            createInterviewSheet(interviewSheet, userId);
            
            // 创建匹配结果工作表
            Sheet matchSheet = workbook.createSheet("岗位匹配");
            createMatchSheet(matchSheet, userId);
            
            // 创建统计汇总工作表
            Sheet statsSheet = workbook.createSheet("统计汇总");
            createStatsSheet(statsSheet, userId);
            
            // 输出到字节数组
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            workbook.write(outputStream);
            return outputStream.toByteArray();
            
        } catch (IOException e) {
            throw new RuntimeException("生成Excel报告失败", e);
        }
    }
    
    /**
     * 创建面试结果工作表
     */
    private void createInterviewSheet(Sheet sheet, Long userId) {
        List<InterviewResult> interviews = getUserInterviewResults(userId);
        
        // 创建标题行
        Row headerRow = sheet.createRow(0);
        String[] headers = {"面试时间", "简历文件", "评分", "AI问题数量", "回答完整度"};
        for (int i = 0; i < headers.length; i++) {
            Cell cell = headerRow.createCell(i);
            cell.setCellValue(headers[i]);
        }
        
        // 填充数据
        for (int i = 0; i < interviews.size(); i++) {
            InterviewResult interview = interviews.get(i);
            Row row = sheet.createRow(i + 1);
            
            row.createCell(0).setCellValue(interview.getCreatedAt().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            row.createCell(1).setCellValue(interview.getResumeFilename());
            row.createCell(2).setCellValue(interview.getScore() != null ? interview.getScore() : 0);
            row.createCell(3).setCellValue(interview.getAiQuestions() != null ? interview.getAiQuestions().split("\n").length : 0);
            row.createCell(4).setCellValue(interview.getUserAnswers() != null && !interview.getUserAnswers().trim().isEmpty() ? "完整" : "不完整");
        }
        
        // 自动调整列宽
        for (int i = 0; i < headers.length; i++) {
            sheet.autoSizeColumn(i);
        }
    }
    
    /**
     * 创建匹配结果工作表
     */
    private void createMatchSheet(Sheet sheet, Long userId) {
        List<ResumeMatchResult> matches = getUserMatchResults(userId);
        
        // 创建标题行
        Row headerRow = sheet.createRow(0);
        String[] headers = {"匹配时间", "岗位名称", "公司名称", "总体匹配度", "技能匹配度", "经验匹配度", "学历匹配度"};
        for (int i = 0; i < headers.length; i++) {
            Cell cell = headerRow.createCell(i);
            cell.setCellValue(headers[i]);
        }
        
        // 填充数据
        for (int i = 0; i < matches.size(); i++) {
            ResumeMatchResult match = matches.get(i);
            Row row = sheet.createRow(i + 1);
            
            row.createCell(0).setCellValue(match.getCreatedAt().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            row.createCell(1).setCellValue(match.getJobDescription().getTitle());
            row.createCell(2).setCellValue(match.getJobDescription().getCompanyName());
            row.createCell(3).setCellValue(match.getOverallScore() != null ? match.getOverallScore() : 0);
            row.createCell(4).setCellValue(match.getSkillsScore() != null ? match.getSkillsScore() : 0);
            row.createCell(5).setCellValue(match.getExperienceScore() != null ? match.getExperienceScore() : 0);
            row.createCell(6).setCellValue(match.getEducationScore() != null ? match.getEducationScore() : 0);
        }
        
        // 自动调整列宽
        for (int i = 0; i < headers.length; i++) {
            sheet.autoSizeColumn(i);
        }
    }
    
    /**
     * 创建统计汇总工作表
     */
    private void createStatsSheet(Sheet sheet, Long userId) {
        Map<String, Object> stats = getReportStats(userId);
        
        Row row1 = sheet.createRow(0);
        row1.createCell(0).setCellValue("统计项目");
        row1.createCell(1).setCellValue("数值");
        
        int rowIndex = 1;
        for (Map.Entry<String, Object> entry : stats.entrySet()) {
            Row row = sheet.createRow(rowIndex++);
            row.createCell(0).setCellValue(entry.getKey());
            row.createCell(1).setCellValue(entry.getValue().toString());
        }
        
        sheet.autoSizeColumn(0);
        sheet.autoSizeColumn(1);
    }
    
    /**
     * 获取报告统计数据
     */
    public Map<String, Object> getReportStats(Long userId) {
        Map<String, Object> stats = new HashMap<>();
        
        List<InterviewResult> interviews = getUserInterviewResults(userId);
        List<ResumeMatchResult> matches = getUserMatchResults(userId);
        
        stats.put("面试总次数", interviews.size());
        stats.put("岗位匹配总次数", matches.size());
        
        // 计算平均面试分数
        double avgInterviewScore = interviews.stream()
                .filter(i -> i.getScore() != null)
                .mapToInt(InterviewResult::getScore)
                .average()
                .orElse(0.0);
        stats.put("平均面试分数", String.format("%.1f", avgInterviewScore));
        
        // 计算平均匹配度
        double avgMatchScore = matches.stream()
                .filter(m -> m.getOverallScore() != null)
                .mapToDouble(ResumeMatchResult::getOverallScore)
                .average()
                .orElse(0.0);
        stats.put("平均匹配度", String.format("%.1f%%", avgMatchScore));
        
        // 最高分数
        int maxInterviewScore = interviews.stream()
                .filter(i -> i.getScore() != null)
                .mapToInt(InterviewResult::getScore)
                .max()
                .orElse(0);
        stats.put("最高面试分数", maxInterviewScore);
        
        double maxMatchScore = matches.stream()
                .filter(m -> m.getOverallScore() != null)
                .mapToDouble(ResumeMatchResult::getOverallScore)
                .max()
                .orElse(0.0);
        stats.put("最高匹配度", String.format("%.1f%%", maxMatchScore));
        
        return stats;
    }
}